package com.hue.springbootredisson.controller;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/index")
public class IndexController {
    @Autowired
    private RedissonClient redissonClient;

    @GetMapping("/data")
    public Object data() {
        RLock lock = redissonClient.getLock("data");
        //尝试获取锁
        boolean b = lock.tryLock();
        System.out.println(b);
        try {
            if (b) {
                System.out.println(Thread.currentThread().getName() + "执行任务");
                Thread.sleep(10000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (b) {
                lock.unlock();
            }
        }
        return "获取数据成功";
    }
}
